<?php

namespace App\Http\Controllers\Api;

use App\Constant;
use App\Http\Controllers\Controller;
use App\Models\FrontendUser;
use App\Models\Notice;

class NoticeController extends Controller
{
    /** 查询公告列表 */
    public function listNotices()
    {
        $limit = request()->limit ?: 10;
        $page = request()->page ?: 1;

        $count = $this->getNoticeQuery()->count();
        $list = $this->getNoticeQuery()->orderByDesc('publish_time')
            ->offset($limit * ($page - 1))->limit($limit)
            ->get()
            ->map(function (Notice $notice) {
                return [
                    'id' => $notice->id,
                    'cover_image_url' => $notice->cover_image_url ?: '',
                    'title' => $notice->title,
                    'publish_time' => $notice->publish_time,
                    'to_user_id' => $notice->to_user_id,
                ];
            });

        return [
            'count' => $count,
            'list' => $list,
        ];
    }

    /** 查询公告详情 */
    public function getNotice($id)
    {
        /** @var Notice $notice */
        $notice = $this->getNoticeQuery()->find($id);

        if (!$notice) {
            return [];
        }

        return [
            'id' => $notice->id,
            'publish_time' => $notice->publish_time,
            'title' => $notice->title,
            'content' => $notice->content,
            'cover_image_url' => $notice->cover_image_url ?: '',
            'to_user_id' => $notice->to_user_id,
        ];
    }

    private function getNoticeQuery()
    {
        return Notice::query()
            ->where('agent_id', request()->agent_id)
            ->where(function ($q) {
                /** @var FrontendUser $user */
                $user = \Auth::guard(Constant::GUARD_API)->user();

                return $q->where('to_user_id', 0)
                    ->when($user, function ($q2) use ($user) {
                        return $q2->orWhere('to_user_id', $user->id);
                    });
            })
            ->where('publish_time', '<=', now());
    }
}
